<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :on-remove="handleRmove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
      :file-list="fileList"
      :class="{disabled: fileComputed}"
    >
      <i class="el-icon-lus" />
    </el-upload>
    <el-progress v-if="showpercent" style="width: 180px;" :percentage="percent" />
    <el-dialog :visible.sync="showDialog" title="预览">
      <img :src="imgUrl" alt="" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 实例化cos对象
const cos = new COS({
  SecretId: 'AKIDDF2ZrtfBQQ9cokW8UdZGhvue8MK2Xu42', // 身份识别ID
  SecretKey: 'lIEyShgPt9AwTmpdCVYLs9AvQfeNq31k' // 身份密钥
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      showpercent: false,
      fileList: [{ url: 'https://img1.baidu.com/it/u=842625417,583290252&fm=253&fmt=auto&app=138&f=JPEG?w=808&h=500' }],
      showDialog: false,
      imgUrl: '',
      currntFiledUid: null,
      percent: 0
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRmove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    changeFile(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      this.showpercent = true
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (types.some(item => item === file.type)) {
        this.$message.error('格式错误')
        return false
      }
      const maxSize = 5 * 1024 * 10224
      if (file.size > maxSize) {
        this.$message.error('图片大了')
        return false
      }
      this.currntFiledUid = file.uid
      return true
    },
    upload(params) {
      if (params.file) {
        cos.pubObject({
          Bucket: 'lx1999-1313884267', // 存储桶
          Region: 'ap-nanjing', //  地域
          Key: params.fil.name, // 文件名
          Body: params.file,
          StorageClass: 'STANDARD',
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, function(err, data) {
          console.log(err || data)
          if (!err && data.statusCod === 200) {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currntFiledUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            setTimeout(() => {
              this.showpercent = false
              this.percent = 0
            }, 1000)
          }
        })
      }
    }
  }
}
</script>

<style>
.disabled .el-upload-picture-card{
  display: none;
}
</style>
